<template>
  <div class='g-content-wrapper'>
  <header-top>
      <tab-bar  class="header-tab" :tab-bar="headerTabBar"
        :on-selected="topSelected" specialWid="true"></tab-bar>
  </header-top>

  <div class="g-content">
    <state :type='7'></state>

    <tab-line class="tab-margin" :tab-line="menuTabLine" :on-selected="tabLineSelected"></tab-line>

    <tab-bar v-show = "tabLineIndex == 0" :on-selected="realTimeSelected"></tab-bar>

    <trend-chart v-if = "tabLineIndex == 0"
      :chart-data = "trendChartData" :legendText="legendText" :top-selected="hdTabBarIndex">
    </trend-chart>

    <tab-bar v-show = "tabLineIndex == 1"
      :on-selected="nextDaySelected" :tab-bar="nextDayTabBar"></tab-bar>
    <tommorow-chart v-if = "tabLineIndex == 1"
      :chart-data="tommorowChartData" :category="nextDayIndex"></tommorow-chart>

    <div class="interval" v-show="!tabLineIndex"></div><!--间隔-->

    <stock-distri :options="stkDistriOpts"
      :data="stkDistriData"  v-show="!tabLineIndex"></stock-distri>
    <div class="interval"></div>
    <div class='comment'>
    <h1 class='comment-title'>涨跌</h1>
      <p>数据解盘中，涨跌停股票数量未统计换手率小于0.5%的股票。</p>
    </div>
  </div>
  </div>
</template>

<script>

import headerTop from '@/components/common/HeaderTop'
import state from '@/components/common/State'
import tabBar from '@/components/common/TabBar'
import tabLine from '@/components/common/TabLine'
import stockDistri from '@/components/common/StockDistri'

import trendChart from './children/TrendChart'
import tommorowChart from './children/TommorowChart'
import remoteDAO from '@/common/remoteDAO'
import constant from '@/common/constant'
import { pointFormat } from '@/filters/dataTime'

export default {
  name: 'current-change',
  components: {
    headerTop,
    state,
    tabBar,
    tabLine,
    stockDistri,
    trendChart,
    tommorowChart
  },
  data () {
    return {
      hdTabBarIndex: 0,
      tabLineIndex: 0,
      realTimeIndex: 0,
      nextDayIndex: 0,
      loading: true,
      headerTabBar: [{
        name: '涨跌停'
      }, {
        name: '涨跌幅大于5%'
      }],

      menuTabLine: [{
        name: '当前实时走势'
      }, {
        name: '涨停股次日表现'
      }],

      nextDayTabBar: [
        {name: '1个交易日'},
        {name: '5个交易日'}
      ],

      trendChartData: null,
      tommorowChartData: null,

      stkDistriData: {}
    }
  },
  computed: {
    stkDistriOpts () {
      return {
        title: this.hdTabBarIndex ? '涨幅大于5%股票板块分布' : '涨跌停股票板块分布',
        positiveText: this.hdTabBarIndex ? '涨幅大于5%股票数量' : '涨停股票数量',
        negativeText: this.hdTabBarIndex ? '跌幅大于5%股票数量' : '跌停股票数量'
      }
    },
    legendText () {
      return {
        redText: this.hdTabBarIndex ? '涨幅大于5%' : '涨停',
        greenText: this.hdTabBarIndex ? '跌幅大于5%' : '跌停',
        blueText: ['上证指数', '上证指数', '深证指数', '创业板指数'][this.realTimeIndex]
      }
    }
  },
  methods: {
    // 顶部tabBar选项卡
    topSelected (index) {
      if (index == this.hdTabBarIndex) return;
      this.menuTabLine[1].name = index ? '涨幅大于5%股次日表现' : '涨停股次日表现';

      this.hdTabBarIndex = index;
      this.$store.dispatch('showLoading');
      this.fetchData();
    },
    // 顶部tabLine选项卡
    tabLineSelected (index) {
      if (index == this.tabLineIndex) return;
      this.tabLineIndex = index;
      this.$store.dispatch('showLoading');
      this.fetchData();
    },
    // 实时走势tabBar选项卡(子组件触发)
    realTimeSelected(index) {
      if (index == this.realTimeIndex) return;
      this.realTimeIndex = index;

      this.$store.dispatch('showLoading');
      this.fetchData();
    },
    // 次日、五日表现 tabBar(子组件触发)
    nextDaySelected(index) {
      if (index == this.nextDayIndex) return;
      this.nextDayIndex = index;

      this.$store.dispatch('showLoading');
      this.fetchData();
    },

    async fetchTodayData () {
      try {
        const [index, chart] = await Promise
          .all([
            remoteDAO.getIndexMinList(['sh', 'sh', 'sz', 'cyb'][this.realTimeIndex]),
            remoteDAO.invoke(
              constant.InterfaceEnum.GET_C_TRENDS,
              {
                type: this.hdTabBarIndex,
                market: this.realTimeIndex
              }
            )
          ]);
        let gain = [];
        let slip = [];
        let added = [];
        chart.xtime.forEach((item, index) => {
          if ((item >= '0930' && item <= '1130') || (item > '1300' && item <= '1500')) {
            item == '1130' ? item = '11:30/13:00'
              : item = item.replace(/(\d{2})(\d{2})/, `$1:$2`);

            if (added.indexOf(item) == -1) {
              gain.push([item, chart.gain[index]]);
              slip.push([item, chart.slip[index]]);
              added.push(item)
            }
          }
        });

        if (gain.length == 0) {
          gain.push(['09:30', 0])
          slip.push(['09:30', 0])
        }
        // const gainStr = gain.map(item => item.join('-')).join(';');
        // console.log(gainStr);
        this.trendChartData = {
          gain: gain,
          slip: slip,
          indexData: index.data
        };
      } catch (err) {
        console.log(err)
        this.$store.dispatch('showError')
      }
    },

    async fetchModData () {
      const res = await remoteDAO.invoke(
        constant.InterfaceEnum.GET_C_MO_TRENDS,
        { type: this.hdTabBarIndex }
      );

      this.stkDistriData = res;
    },

    async fetchFutureData () {
      try {
        const [index, chart] = await Promise
          .all([
            !this.nextDayIndex ? remoteDAO.getIndexMinList('sh')
              : remoteDAO.invoke(constant.InterfaceEnum.GET_DAYS_INDEX, {
                type: 1,
                pType: 6 // 获取5天的收盘指数
              }),
            remoteDAO.invoke(
              constant.InterfaceEnum.GET_FUTURE_PF,
              {
                type: this.hdTabBarIndex,
                pType: this.nextDayIndex
              }
            )
          ])

        if (!chart) {
          throw new Exception();
        }
        let average = [];
        let added = []
        chart.xtime.forEach((item, index) => {
          if (this.nextDayIndex == 0) {
            if ((item >= '0930' && item <= '1130') || (item > '1300' && item <= '1500')) {
              item == '1130' ? item = '11:30/13:00'
                : item = item.replace(/(\d{2})(\d{2})/, `$1:$2`);

              if (added.indexOf(item) == -1) {
                average.push([item, chart.average[index]]);
                added.push(item)
              }
            }
          } else {
            average.push([pointFormat(item), chart.average[index]]);
          }
        });
        if (average.length == 0 && this.nextDayIndex == 0) {
          average.push(['09:30', 0])
        }
        // 取六天指数数据，最后一天时间不等于涨跌幅时间，就丢弃，否则丢弃第一天的
        let indexData = index.TableInfo;
        if (this.nextDayIndex && indexData.length > 0) {
          indexData[indexData.length - 1].date != chart.xtime.slice(chart.xtime.length - 1) ? indexData.splice(-1, 1) : indexData.splice(0, 1)
        }

        this.tommorowChartData = {
          xtime: !this.nextDayIndex ? chart.xtime : indexData.map(item => item.date),
          average: average,
          lastData: chart.lastData,
          indexData: this.nextDayIndex ? indexData.map(item => item.price) : index.data.index
        };
      } catch (err) {
        console.log(err)
        this.$store.dispatch('showError')
      }
    },

    fetchData () {
      if (this.tabLineIndex) {
        this.$loop.unregister(this.fetchTodayData, this.fetchModData);
        this.nextDayIndex ? this.fetchFutureData() : this.$loop.register(this.fetchFutureData);
      } else {
        this.$loop.unregister(this.fetchFutureData);
        this.$loop.register(this.fetchTodayData, this.fetchModData);
      }
    }
  },
  mounted () {
    this.fetchData();
  }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
@import '../../assets/css/common.less';
.header-tab {
  margin-top: 0.07rem;
}
.g-content {
  .box {
    margin: .2rem 0;
  }
}
</style>
